package com.chookss.mine;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.inspection.InspectionHomeActivity;
import com.chookss.mine.adapter.MineAdapter;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.mine.entity.MineNavigationEntity;
import com.chookss.mine.personal.collection.MyCollectionActivity;
import com.chookss.mine.set.SettingActivity;
import com.chookss.mine.set.UserInfosActivity;
import com.chookss.mine.system.MyNoticeActivity;
import com.chookss.mine.system.MyPraiseActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.InitDialog;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.johnrambo.ktea.ktExtends.ShareUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MineFragment extends ImmersionFragment {

    @BindView(R.id.rl_mine_top)
    RelativeLayout rl_mine_top;
    @BindView(R.id.llSetting)
    LinearLayout llSetting;
    @BindView(R.id.llBack)
    LinearLayout llBack;
    @BindView(R.id.ivMessage)
    ImageView ivMessage;
    @BindView(R.id.ivSign)
    ImageView ivSign;
    @BindView(R.id.rlMessage)
    RelativeLayout rlMessage;
    @BindView(R.id.ivUserImg)
    CircleImageView ivUserImg;
    @BindView(R.id.tvUserName)
    TextView tvUserName;
    @BindView(R.id.tvUserId)
    TextView tvUserId;
    @BindView(R.id.tvPraiseNum)
    TextView tvPraiseNum;
    @BindView(R.id.tvFocusOnNum)
    TextView tvFocusOnNum;
    @BindView(R.id.tvFansNumb)
    TextView tvFansNumb;
    @BindView(R.id.tvCollectNum)
    TextView tvCollectNum;
    @BindView(R.id.tv_mine_sign_in)
    TextView tvMineSignIn;
    @BindView(R.id.ll_mine_sign_in)
    LinearLayout llMineSignIn;
    @BindView(R.id.tvLearnDay)
    TextView tvLearnDay;
    @BindView(R.id.tvLearnTime)
    TextView tvLearnTime;
    @BindView(R.id.tvSubjectNum)
    TextView tvSubjectNum;
    @BindView(R.id.rvKnowledge)
    RecyclerView rvKnowledge;
    @BindView(R.id.rvLearn)
    RecyclerView rvLearn;
    @BindView(R.id.rvWork)
    RecyclerView rvWork;
    @BindView(R.id.tvWork)
    TextView tvWork;
    @BindView(R.id.tvLearn)
    TextView tvLearn;
    @BindView(R.id.rlUpload)
    RelativeLayout rlUpload;
    @BindView(R.id.ivUpload)
    ImageView ivUpload;

    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    private Context mContext;
    Unbinder unbinder;
    private String employeeCode;
    private MineInfoEntity mineInfoEntity;
    private List<MineNavigationEntity> knowledgeLists = new ArrayList<>();
    private List<MineNavigationEntity> learnLists = new ArrayList<>();
    private List<MineNavigationEntity> workLists = new ArrayList<>();
    private MineAdapter knowledgeAdapter;
    private MineAdapter learnAdapter;
    private MineAdapter workAdapter;

    public MineFragment() {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        init();
        return view;
    }

    private void init() {
        //顶部状态栏 处理
        int statusBarHeight = Utils.getStatusBarHeight(mContext);
        RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) rl_mine_top.getLayoutParams();
        topAllParams.setMargins(0, statusBarHeight, 0, 0);
        rl_mine_top.setLayoutParams(topAllParams);
        llMineSignIn.setVisibility(View.VISIBLE);
        llSetting.setVisibility(View.VISIBLE);
        rlMessage.setVisibility(View.VISIBLE);
        //导航
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);
        rvKnowledge.setLayoutManager(gridLayoutManager);
        knowledgeAdapter = new MineAdapter(R.layout.item_mine, mContext, knowledgeLists);
        rvKnowledge.setAdapter(knowledgeAdapter);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(mContext, 4);
        rvLearn.setLayoutManager(gridLayoutManager2);
        learnAdapter = new MineAdapter(R.layout.item_mine, mContext, learnLists);
        rvLearn.setAdapter(learnAdapter);
        GridLayoutManager gridLayoutManager3 = new GridLayoutManager(mContext, 4);
        rvWork.setLayoutManager(gridLayoutManager3);
        workAdapter = new MineAdapter(R.layout.item_mine, mContext, workLists);
        rvWork.setAdapter(workAdapter);
        initAdapter();
        //上传失败的全部给与状态2
        XJson.setUploadEntity(mContext, UploadEntity.class);
    }

    private void initAdapter() {
        if (tvWork == null) {
            return;
        }
        knowledgeLists.clear();
        knowledgeLists.addAll(NavigationTools.getMineKnowledge(mContext));
        knowledgeAdapter.notifyDataSetChanged();
        learnLists.clear();
        learnLists.addAll(NavigationTools.getMineLearn(mContext));
        workLists.clear();
        workLists.addAll(NavigationTools.getMineWork(mContext));
        if (learnLists.size() == 0) {
            tvLearn.setVisibility(View.GONE);
            rvLearn.setVisibility(View.GONE);
        } else {
            tvLearn.setVisibility(View.VISIBLE);
            rvLearn.setVisibility(View.VISIBLE);
            learnAdapter.notifyDataSetChanged();
        }
        if (workLists.size() == 0) {
            tvWork.setVisibility(View.GONE);
            rvWork.setVisibility(View.GONE);
        } else {
            tvWork.setVisibility(View.VISIBLE);
            rvWork.setVisibility(View.VISIBLE);
            workAdapter.notifyDataSetChanged();
        }
        if (!Utils.isNull(employeeCode)) {
            learnAdapter.setEmployeeCode(employeeCode);
            knowledgeAdapter.setEmployeeCode(employeeCode);
            if (workLists.size() > 0) {
                workAdapter.setEmployeeCode(employeeCode);
            }
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        employeeCode = new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
        getData();
        List<UploadEntity> uploadEntities = XJson.getUploadEntity(mContext, UploadEntity.class);
        if (uploadEntities.size() > 0) {
            ivUpload.setVisibility(View.VISIBLE);
        } else {
            ivUpload.setVisibility(View.GONE);
        }

    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", employeeCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.getMyInfo, SignUtils2.makeSignStr(map), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) {
                mineInfoEntity = data;
                updateData(mineInfoEntity);
            }

            @Override
            public void onError(String errorMsg) {
            }
        });

    }

    private void updateData(MineInfoEntity mineInfoEntity) {
        if (mineInfoEntity == null) {
            return;
        }
        tvUserName.setText(mineInfoEntity.getNickName());
        if (mContext.getPackageName().equals("com.zhaofengnum")) {
            tvUserId.setText(mContext.getResources().getString(R.string.app_name));
        } else {
            tvUserId.setText(new ShareUtils().getString(mContext, StaticClass.COMPANYNAME, ""));
        }
        tvFansNumb.setText(mineInfoEntity.getFansNum());
        tvFocusOnNum.setText(mineInfoEntity.getFocusOnNum());
        tvPraiseNum.setText(mineInfoEntity.getGetPraiseNum());
        tvCollectNum.setText(mineInfoEntity.getCollectNum());
        tvMineSignIn.setText(mineInfoEntity.getLvlName());
        tvLearnDay.setText(Utils.changeNumber(mineInfoEntity.getStudyDays()) + "");
        tvLearnTime.setText(mineInfoEntity.getStudyTime());
        tvSubjectNum.setText(Utils.changeNumber(mineInfoEntity.getAnswerNum()) + "");
        GlideUtils.loadAvatar(mContext, mineInfoEntity.getHeadPhotoThumbUrl(), ivUserImg);
        new ShareUtils().putString(mContext, StaticClass.APPACCOUNT, mineInfoEntity.getAppAccount());
        new ShareUtils().putString(mContext, StaticClass.DEVICENAME, mineInfoEntity.getBindingDeviceName());
        int unRead = Utils.changeNumber(mineInfoEntity.getUnReadNum());
        if (unRead > 0) {
            ivMessage.setVisibility(View.VISIBLE);
        } else {
            ivMessage.setVisibility(View.GONE);
        }
        if (!Utils.isNull(mineInfoEntity.getLvlImage())) {
            String url = mineInfoEntity.getLvlImage();
            GlideUtils.load(mContext, url, ivSign, R.drawable.icon_wangzhe_23);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("updateNavigation".equals(msg)) {
                //更新导航
                employeeCode = new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
                initAdapter();
            } else if ("refreshUploadRecord".equals(messageEvent.getMessage())) {
                List<UploadEntity> uploadEntities = XJson.getUploadEntity(mContext, UploadEntity.class);
                if (uploadEntities.size() > 0) {
                    ivUpload.setVisibility(View.VISIBLE);
                } else {
                    ivUpload.setVisibility(View.GONE);
                }
            }
        }
    }


    @OnClick({R.id.llSetting, R.id.rlMessage, R.id.rlUpload, R.id.llBack, R.id.ivUserImg, R.id.tvUserName, R.id.llPraise, R.id.llMyFocus, R.id.llFans, R.id.llCollect, R.id.ll_mine_sign_in, R.id.llLearnDay, R.id.llLearnTime, R.id.llSubjectNum})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.llSetting:
                intent = new Intent(mContext, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.rlMessage:
                if (ivMessage == null) {
                    return;
                }
                ivMessage.setVisibility(View.GONE);
                intent = new Intent(mContext, MyNoticeActivity.class);
//                intent = new Intent(mContext, ShopServiceActivity.class);
                startActivity(intent);
                break;
            case R.id.rlUpload:
//                intent = new Intent(mContext, MyUploadRecordActivity.class);
                intent = new Intent(mContext, InspectionHomeActivity.class);
                startActivity(intent);
                break;
            case R.id.llBack:
                break;
            case R.id.ivUserImg:
            case R.id.tvUserName:
                intent = new Intent(mContext, UserInfosActivity.class);
                startActivity(intent);
                break;
            case R.id.llPraise:
                intent = new Intent(mContext, MyPraiseActivity.class);
                intent.putExtra("messageType", 2);
                startActivity(intent);
                break;
            case R.id.llMyFocus:
                intent = new Intent(mContext, MyPraiseActivity.class);
                intent.putExtra("messageType", 5);
                startActivity(intent);
                break;
            case R.id.llFans:
                intent = new Intent(mContext, MyPraiseActivity.class);
                intent.putExtra("messageType", 1);
                startActivity(intent);
                break;
            case R.id.llCollect:
//                intent = new Intent(mContext, SearchVideoResultActivity.class);
                intent = new Intent(mContext, MyCollectionActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.ll_mine_sign_in:
                if (PermissionSpUtils.getBoolean(mContext,"08",false)) {
                    //有个人能力权限才可点击
                    intent = new Intent(mContext, WebCommonActivity.class);
                    intent.putExtra("url", NavigationTools.getAllUrl(mContext, Urls.getCapacityAnalysisGrowth) + "&employeeCode=" + new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, ""));
                    intent.putExtra("title", "段位");
                    startActivity(intent);
                }

                break;
            case R.id.llLearnDay:
                new InitDialog(mContext, "学习天数", mContext.getString(R.string.mine_learnday), "确定").show();
                break;
            case R.id.llLearnTime:
                new InitDialog(mContext, "学习时长", mContext.getString(R.string.mine_learntime), "确定").show();
                break;
            case R.id.llSubjectNum:
                new InitDialog(mContext, "做题量", mContext.getString(R.string.mine_subjectnum), "确定").show();
                break;
        }
    }

    @Override
    public void initImmersionBar() {
        if (getActivity() == null) {
            return;
        }
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(false)
                .flymeOSStatusBarFontColor(R.color.white)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        EventBus.getDefault().unregister(this);
    }
}
